<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:set value="<%=request.getContextPath()%>" var="ctx"></c:set>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>添加商家信息</title>
<script type="text/javascript"
	src="${ctx}/assert/js/jquery.validate.min.js"></script>
<script type="text/javascript" src="${ctx}/assert/js/common.js"></script>
<link rel="stylesheet" type="text/css" href="${ctx}/decorators/css/plugins/toastr/toastr.min.css"></link>
<link rel="stylesheet" type="text/css" href="${ctx}/webuploader/css/webuploader.css"/>
<link rel="stylesheet" type="text/css" href="${ctx}/webuploader/css/webuploader-demo.css"/>
<script type="text/javascript" src="${ctx}/webuploader/js/webuploader.min.js" ></script>
<script type="text/javascript" src="${ctx}/webuploader/js/webuploader-demo-addVendor.js" ></script> 
<script src="${ctx}/decorators/js/plugins/toastr/toastr.min.js"></script>
<script type="text/javascript">
	$(document).ready(function() {

		$("#myform").validate({
			debug : false,
			rules : {
				vName : {
					required : true,
					minlength : 2,
					maxlength : 20,
					checkName : true
				},
				website : {
					minlength : 9,
					maxlength : 30,
					isWebsite : true
				},
				address : {
					required : true,
					minlength : 1,
					maxlength : 50
				},
				linkman : {
					required : true,
					minlength : 2,
					maxlength : 10
				},
				info : {
					required : true,
					minlength : 1,
					maxlength : 500
				},
				businessLicence : {
					required : true,
					minlength : 1,
					maxlength : 30
				},
				tel : {
					required : true,
					isMobile : true,
				},
				cName : {
					required : true,
					minlength : 1,
					maxlength : 20
				},
				cValue : {
					required : true,
					minlength : 1,
					maxlength : 500
				}
			},
			messages : {
				vName : {
					required : "请输入公司名称",
					minlength : "公司名称最小为2位",
					maxlength : "公司名称最大为20位",
					checkName : "公司名称不能包含'\\'或者'.'"
				},
				website : {
					minlength : "请正确填写您的网址",
					maxlength : "网址最大为30位",
					isWebsite : "请正确填写您的网址"
				},
				address : {
					required : "请输入公司地址",
					minlength : "公司地址最小为1位",
					maxlength : "公司地址最大为50位"
				},
				linkman : {
					required : "请输入联系人",
					minlength : "联系人最小为2位",
					maxlength : "联系人最大为10位"
				},
				info : {
					required : "请输入公司简介",
					minlength : "公司简介最小为1位",
					maxlength : "公司简介最大为500位"
				},
				businessLicence : {
					required : "请输入公司营业执照",
					minlength : "营业执照最小为1位",
					maxlength : "营业执照最大为30位"
				},
				tel : {
					required : "请输入联系电话",
					isMobile : "请正确填写您的联系电话",
				},
				cName : {
					required : "请输入字段名",
					minlength : "字段名最小为1位",
					maxlength : "字段名最大为20位"
				},
				cValue : {
					required : "请输入字段信息",
					minlength : "字段名最小为1位",
					maxlength : "字段名最大为500位"
				}
			}
		});

	})

	//验证工商字号只能输入英文或数字
	jQuery.validator.addMethod("isEnNum", function(value, element) {
		var enNum = /[A-Za-z0-9]$/;
		return this.optional(element) || (enNum.test(value));
	}, "工商字号只能输入字母或数字");
	
	jQuery.validator.addMethod("isWebsite", function(value, element) {
		var enNum = /((http|ftp|https):\/\/)?[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/;
		return this.optional(element) || (enNum.test(value));
	}, "请输入正确网址");

	//验证厂商名称是否包含“.”或者“\”
	jQuery.validator.addMethod("checkName", function(value, element) {
		var bool = false;
		if (value.indexOf("\\") == -1) {
			if (value.charAt(value.length - 1) == ".") {
				bool = false;
			} else {
				bool = true;
			}
		}
		return bool;
	}, "厂商名称不能包含'\'或者'.'");

	jQuery.validator.addMethod(
					"isMobile",
					function(value, element) {
						var length = value.length;
						var tel = /^((0[0-9]{2,3})-(\d{7,8}))|((0[0-9]{2,3})(\d{7,8}))$/;
						var mobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
						return (mobile.test(value) || tel.test(value)) ? true
								: false;
					}, "请正确填写您的手机号码");

	/**
	 * 保存厂商
	 */
	function saveVendor() {
		var vendorName = $("#vName").val();
		var vendorId = $("#id").val();

		if (isEmpty(vendorId)) {
			vendorId = 0;
		}
		//表单验证
		if (!$("#myform").valid()) {
			//			alert(vendorName);
			return;
		}

		$.ajax({
			type : "POST",
			url : "checkVendorName", //换成你要请求的action, paperId 是url参数
			data : {
				'id' : vendorId,
				'vName' : vendorName
			},
			dateType : 'text',
			error : function(msg) {
				toastr.error("保存失败！")
			},
			success : function(data) {
				if (data == 'success') {
					saveForm();
					//document.myform.submit();					
				} else {
					$("#msgDiv").show();
					$("#errMsg").html("系统中有重复的公司名称，请重新输入");
					$("#errMsg").show();
					$("#vName").select();
				}
			}
		});
	}

	function saveForm(){
		var formdata = new FormData($("#myform")[0]);
		$.ajax({
		    url: 'addVendor',
		    type: 'POST',
		    data: formdata,
		    async: false,
		    contentType: false,
		    processData: false,
		    success: function(msg) {
		        if(msg == "success"){
		        	if($("#uploader img").length == 0){
		        		window.location.href="vendorList";
		        	}else{
			        	$(".uploadBtn").click();		        		
		        	}
		        }
		    },
		    error: function(data) {
		    	toastr.error("网络连接失败");
		    }
		});
	}
	
	
	/**
	 * 图片预览
	 */
	function previewImage(imgFile) {
		//清除错误消息
		document.getElementById("errDiv").style.display = "none";
		$("#error").html("");
		var pattern = /(\.*.jpg$)|(\.*.png$)|(\.*.jpeg$)|(\.*.gif$)|(\.*.bmp$)/;
		if (!pattern.test(imgFile.value)) {
			$("#errDiv").show();
			$("#error").html("系统仅支持jpg/jpeg/png/gif/bmp格式的照片！");
			$("#error").show();
			imgFile.focus();
			document.getElementById("file").value = "";
		} else {
			var path;
			//IE
			if (document.all) {
				imgFile.select();
				path = document.selection.createRange().text;
				document.getElementById("imgPreview").innerHTML = "";
				document.getElementById("imgPreview").style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='scale',src=\""
						+ path + "\")";//使用滤镜效果 
			} else {
				path = URL.createObjectURL(imgFile.files[0]);
				document.getElementById("imgPreview").innerHTML = "<img src='"+path+"' width='150px' height='100px'/>";
				document.getElementById("removeImageBtn").style.display = "";
				document.getElementById("uploadImage").style.display = "none";
				document.getElementById("imageDiv").style.display = "none";
				document.getElementById("productImage").value = null;
			}
		}
	}

	/**
	 * 移除图片
	 */
	function removeImage(sign) {
		if (sign == 1) {
			document.getElementById("imgPreview").innerHTML = "";
			document.getElementById("removeImageBtn").style.display = "none";
			document.getElementById("file").value = "";
		} else {
			document.getElementById("imageDiv").style.display = "none";
			document.getElementById("vendorImage").value = null;
		}
	}

	/*
	 *新增字段
	 */
	function addColumn() {
		if (!$("#myform").valid()) {
			return;
		}
		
		var length = document.getElementsByName("cName").length;
		if(length > 0){
			for(var i=0;i<length;i++){
				var val = document.getElementsByName("cName")[i].value;
				var val1 = document.getElementsByName("cValue")[i].value
				if(isEmpty(val) || isEmpty(val1)){
					return;
				}
			}			
		}

		//var infoDiv = $('#infoDiv');
		var formGroup = $("#colSpan .form-group:last");
		
		var str = '<div class="form-group">\
						<div class="col-sm-6">\
							<input type="text" class="form-control" placeholder="请输入字段名" name="cName" style="  text-align: right;"  />\
						</div>\
						<div class="col-sm-4">\
							<input type="text" class="form-control" placeholder="请输入新增信息"	name="cValue"  />\
						</div>\
						<button onclick="delColumn(this);return false;" class="btn btn-danger btn-xs">删除</button>\
						<input type="hidden" name="eId" value="0"/>\
					</div>';
		//infoDiv.before(str);
		formGroup.after(str);
	}

	//删除自定义属性
	function delColumn(nowTr) {
		var id = $(nowTr).next().val();
		//			alert(id);
		if (id == undefined || id == 0) {
			$(nowTr).parent().remove();
			return;
		}
		$.ajax({
			type : "POST",
			url : "delExtraColumn", //换成你要请求的action, paperId 是url参数
			data : {
				'id' : id
			},
			error : function(msg) {
				toastr.error("删除失败！")
			},
			success : function(msg) {
				if (msg == "success") {
					toastr.success("属性删除成功")
				} else {
					toastr.error("删除失败！")
					return;
				}
			}
		})

		$(nowTr).parent().remove();
	}

	/**
	 *检查公司名称
	 */
	function checkvName() {
		$('#saveBtn').removeAttr("disabled");

		var vName = $('#vName').val();
		//			alert(vName);
		if (vName == "" || vName == 'undefined') {
			return;
		}
		$.ajax({
			type : "POST",
			url : "checkVendorName", //换成你要请求的action, paperId 是url参数
			data : {
				'vName' : vName
			},
			error : function(msg) {
				toastr.error("用户名重复！")

			},
			success : function(msg) {
				if (msg == "success") {
					//alert("用户名可用")
				} else {
					toastr.error("用户名重复")
					$('#saveBtn').attr('disabled', true);
				}

			}
		});

	}
	
	
	function delImg(id){
		//alert(id);
		
		$.ajax({
			type : "POST",
			url : "delImg", //换成你要请求的action, paperId 是url参数
			data : {
				'id' : id
			},
			error : function(msg) {
				toastr.error("网络连接失败");				
			},
			success : function(msg) {
				if(msg == "success"){
					$("#img"+id+" img" ).attr("src","")
					$("#img"+id).html("");
				}else{
					toastr.error("删除图片失败");
				}
				
			}
		});
	}
</script>
</head>
<body>
      <div class="row">
            <div class="col-lg-12">
               <div class="row wrapper border-bottom white-bg ibox-title">
                         <div class="col-lg-11">
                             <h3>新增商家信息</h3>
                         </div>
                         <div class="col-lg-1">
                             <a class="btn btn-success btn-block" href="${ctx}/admin/vendorList">返回列表
                             </a>
                         </div>
                </div>


			     <div class="wrapper wrapper-content animated fadeInRight">
                      <div class="ibox-title">
						<form class="form-horizontal wrapper-content" role="search" action="saveVendor"
							method="post" name="myform" id="myform"
							enctype="multipart/form-data">
							<input type="hidden" name="id" value="${vendorView.vendor.id }"
								id="id" />
							<div style="display: none" id="msgDiv">
								<label id="errMsg" style="color: red"></label>
							</div>
							
							
							<div class="row">
							  <div class="col-lg-6" id="colSpan">
	                           <div class="form-group">
								<label for="vName" class="col-sm-6 control-label"><font
									color=red>*</font>公司名称：</label>
								<div class="col-sm-6">
									<input type="text" class="form-control " name="vName"
										value="${vendorView.vendor.VName }" id="vName"
										onblur="checkvName();" placeholder="请输入公司名称">
								</div>
	
							</div>
				


							<div class="form-group">
								<label for="address" class="col-sm-6 control-label"><font
									color=red>*</font>通信地址：</label>
								<div class="col-sm-6">
									<input type="text" class="form-control " placeholder="请输入公司地址"
										name="address" value="${vendorView.vendor.address }"
										id="address" />
								</div>
							</div>
				


							<div class="form-group">
								<label for="businessLicence" class="col-sm-6 control-label"><font
									color=red>*</font>营业执照：</label>
								<div class="col-sm-6">
									<input type="text" class="form-control " placeholder="请输入营业执照"
										name="businessLicence"
										value="${vendorView.vendor.businessLicence }"
										id="businessLicence" />
								</div>
							</div>



							<div class="form-group">
								<label for="linkman" class="col-sm-6 control-label"><font
									color=red>*</font>联 系 人：</label>
								<div class="col-sm-6">
									<input type="text" class="form-control " placeholder="请输入联系人姓名"
										name="linkman" value="${vendorView.vendor.linkman }"
										id="linkman" />
								</div>
							</div>
	


							<div class="form-group">
								<label for="tel" class="col-sm-6 control-label"><font
									color=red>*</font>联 系 电 话：</label>
								<div class="col-sm-6">
									<input type="text" class="form-control " placeholder="请输入联系电话"
										name="tel" value="${vendorView.vendor.tel }" id="tel" />
								</div>
							</div>
	



							<div class="form-group">
								<label for="vendorUrl" class="col-sm-6 control-label">网
									址：</label>
								<div class="col-sm-6">
									<div class="row">
									       <div class="col-lg-7">
											<input type="text" class="form-control " placeholder="请输入网址"
												name="website" value="${vendorView.vendor.website }"
												id="website" />
											</div>
										
										<div class="col-lg-5">
										    <button type="button" class="btn btn-primary btn-sm"  onclick="addColumn();" data-toggle="modal">新增信息</button>
									    </div>
								</div>
							</div>
	                       </div>
							  </div>
							  <div class="col-lg-6">
							<div class="form-group" id="infoDiv">
								<label for="postcode" class="col-sm-2 control-label"><font
									color=red>*</font>公司简介：</label>
								<div class="col-sm-10">
									<textarea rows="5" cols="1" class="form-control"
										maxlength="500" placeholder="请输入公司简介"
										aria-describedby="basic-addon1" name="info" id="info">${vendorView.vendor.info}</textarea>
								</div>
							</div>


							<div class="form-group">
								<label for="postcode" class="col-sm-2 control-label">公司logo：</label>
								<div class="col-sm-10">
									<input type="file" name="file" id="file"  style="width: 200px;"onchange='previewImage(this)' />
								</div>
								<div style="display: none" id="errDiv">
									<label id="error" style="color: red"></label>
								</div>

								
							</div>
							
								<div class="form-group">
								        <div class="col-sm-2"></div>
								        <div class="col-sm-10">
												<div id="imgPreview"></div>
													<div class="removeImg" style="margin:10px 0;">
														<input type="button" class="btn btn-danger btn-xs" value="移除"
															style="display: none;"
															onclick="removeImage(1)" id="removeImageBtn" />
														<c:if test="${not empty vendorView.vendor.logo}">
															<div id="imageDiv">
																<img src="${imageUrl}${vendorView.vendor.logo}"
																	style="width: 150px; height: 100px; float: left"
																	id="uploadImage"> <input type="hidden" name="img"
																	id="img" value="${vendorView.vendor.logo}" /> <input
																	type="button" class="btn btn-danger btn-xs" value="移除"
																	onclick="removeImage(2)" style="margin: 60px 15px 0;" />
															</div>
														</c:if>
													</div>
												
								        </div>
								</div>
							  </div>
							  
							  <div class="ibox">	

								<div class="ibox-content">
									<div class="page-container">
										<p>您可以尝试文件拖拽，使用QQ截屏工具，然后激活窗口后粘贴，或者点击添加图片按钮</p>
										<div id="uploader" class="wu-example">
											<div class="queueList">
												<div id="dndArea" class="placeholder">
													<div id="filePicker" class="webuploader-container">
													<div class="webuploader-pick" style=" position: relative;">
													点击选择图片	
													<div id="rt_rt_1aa3dju5ks4pt80p7p1nsr1m6e1" 
															style="position: absolute; top: 0px; left: 317px; width: 168px; height: 44px; overflow: hidden; bottom: auto; right: auto;">
															<input type="file" name="file" class="webuploader-element-invisible" multiple="multiple" accept="image/*">
															<label style="opacity: 0; width: 100%; height: 100%; display: block; cursor: pointer; background: rgb(255, 255, 255);"></label>
													</div>
													</div>
	
													</div>
													<p>或将照片拖到这里，单次最多可选300张</p>
												</div>
											<ul class="filelist"></ul></div>
											<div class="statusBar" style="display:none;">
												<div class="progress" style="display: none;">
													<span class="text">0%</span>
													<span class="percentage" style="width: 0%;"></span>
												</div>
												<div class="info">共0张（0B），已上传0张</div>
												<div class="btns">
													<div id="filePicker2" class="webuploader-container"><div class="webuploader-pick">继续添加</div><div id="rt_rt_1aa3dju5onv6bep8t06qtee36" style="position: absolute; top: 0px; left: 0px; width: 1px; height: 1px; overflow: hidden;"><input type="file" name="file" class="webuploader-element-invisible" multiple="multiple" accept="image/*"><label style="opacity: 0; width: 100%; height: 100%; display: block; cursor: pointer; background: rgb(255, 255, 255);"></label></div></div>
													<button type="button" class="uploadBtn state-pedding" style=" display:none;">开始上传</button>
												</div>
											</div>
										</div>
									</div>
	
								</div>
							</div>
							  
							  
							</div>

								<div class="form-group text-center">
				
										<button type="button" class="btn btn-primary" id="saveBtn"onclick="saveVendor()">&#12288;保存&#12288;</button>
				
								</div>
							
							
						</form>
					</div>
				</div>
			</div>
		</div>
	
</body>
</html>
